﻿
var clear_fields_on_new, col_names, col_model, details_form_options,
        edit_fields_model, possible_values_for_assocs;

var _custom_html_fields = new Array();


function create_html_for_cmb(field_id, field_name, id_label_pairs) {
    //Sort the pairs
    id_label_pairs = id_label_pairs.sort(function(a, b) {
        if (a.Label == b.Label)
            return 0;
        else if (a.Label < b.Label)
            return -1;
        else if (a.Label > b.Label)
            return 1;
    }
             );

    html_txt = "<select id=\"" + field_id +
            "\" name=\"" + field_name +
            "\" >";
    html_txt += '<option value=""></option>';
    $.each(id_label_pairs, function(index, id_label_pair) {
        html_txt += '<option value="' + id_label_pair.ID + '">' + id_label_pair.Label + '</option>';
    });
    html_txt += '</select>';
    return html_txt
}

function create_html_for_text_field(field_id, field_name, width) {
    return "<input id=\"" + field_id +
            "\" name=\"" + field_name +
            "\" width=\"" + width + "px\" />";
}



function reset_grid_and_form(message) {
    alert(message);
    $("#list").trigger("reloadGrid");
    if (clear_fields_on_new)
        $("#details_form").resetForm();
}

function EditFieldDescriptor(index, name, width)
{
    this.index = "";
    this.name = "";
    this.width = "";
}

function generate_edit_form(edit_fields_model, custom_html_fields, possible_values_for_assocs) {

    //Add the edit form at the top of the table
    txt_fields = "<fieldset><legend>Fields</legend>";
    for (var col_idx = 0; col_idx < edit_fields_model.length; col_idx++) {
        curr_col_model = edit_fields_model[col_idx];
        txt_fields += "<div class=\"edit_form_field\"><label>" + curr_col_model.name + "</label>";
        if (possible_values_for_assocs[curr_col_model.index] == null) {
            //check if a custom html field builder is registered for this field
            if (_custom_html_fields[curr_col_model.index] != null) {
                txt_fields += custom_html_fields[curr_col_model.index](curr_col_model.index +
                    "_field", curr_col_model.index, curr_col_model.width);
            }
            else {
                //Do normal textbox for non-association field
                txt_fields += create_html_for_text_field(curr_col_model.index +
                    "_field", curr_col_model.index, curr_col_model.width);
            }
        }
        else {
            txt_fields += create_html_for_cmb(curr_col_model.index +
                    "_field", curr_col_model.index, possible_values_for_assocs[curr_col_model.index]);
        }
        txt_fields += "</div>";
    }
    txt_fields += "</fieldset><div style=\"clear: both\"></div>";
    return txt_fields;
}

function setup_grid(grid_data_url, grid_rows_per_page,
        icons_base_path, grid_caption) {
    //Set up the grid
    $("#list").jqGrid({
        url: grid_data_url,
        datatype: 'json',
        myType: 'GET',
        colNames: col_names,
        colModel: col_model,
        pager: $('#pager'),
        rowNum: grid_rows_per_page,
        rowList: [5, 10, 15],
        sortname: 'id',
        sortorder: 'desc',
        viewrecords: true,
        multiselect: true,
        imgpath: icons_base_path,
        caption: grid_caption,
        onSelectRow: show_record_in_form

    });
    txt_fields = generate_edit_form(edit_fields_model, _custom_html_fields, possible_values_for_assocs);
    $("#details_form_fields").html(txt_fields);
    // prepare Options Object
    details_form_options = {
        url: '',
        dataType: 'json',
        success: function() {
            alert('Changes submitted!');
        }
    };
    $("#save_new_form_btn").click(function(e) {
        // stop normal link click
        e.preventDefault();
        $('#details_form').ajaxSubmit(prepare_options_for_form('Create',
              'Record created succesfully!'));
    });

    $("#save_form_btn").click(function(e) {
        // stop normal link click
        e.preventDefault();
        $('#details_form').ajaxSubmit(prepare_options_for_form(
            "Edit/" + _curr_selected_record_id,
              'Record saved succesfully!'));
    });

    $("#save_form_multiple_btn").click(function(e) {
        // stop normal link click
        e.preventDefault();
        var crud_model_id = -1;
        var selected_ids = get_ids_of_selected_records();

        $('#ids_to_change').val(selected_ids.join(','));
        details_form_options.url = "EditMultiple";
        details_form_options.success = function() {
            reset_grid_and_form('Records saved succesfully!');
        };
        $('#details_form').ajaxSubmit(details_form_options);
    });

    $("#delete_btn").click(function(e) {
        e.preventDefault();

        var answer = confirm("Are you sure you want to delete the selected records?");

        if (answer) {
            var crud_model_id = -1;
            var ids = get_ids_of_selected_records();
            //var form = document.getElementById('crud_grid');
            var ids_to_delete_field = document.getElementById('ids_to_delete');

            ids_to_delete_field.value = ids.join(',');
            details_form_options.url = "Delete";
            details_form_options.success = function() {
                reset_grid_and_form('Records were deleted!');
            };
            $('#delete_form').ajaxSubmit(details_form_options);
        }
    });
}


function get_ids_of_selected_records() {
    var ids = new Array();

    $(".cbox:checkbox:checked").each(function() {
        crud_model_id = this.id.replace("jqg_", "");
        ids.push(crud_model_id);
    });
    return ids;
}

var _curr_selected_record_id = -1;
function show_record_in_form(crud_model_id) {
    _curr_selected_record_id = crud_model_id;
    var row_data = $("#list").getRowData(crud_model_id);
    for (var col_idx = 0; col_idx < col_model.length; col_idx++) {
        col_value = row_data[col_model[col_idx].name];
        col_field_id = col_model[col_idx].index + "_field";
        $("#" + col_field_id).val($.trim(col_value));
    }
}

var _before_form_submit_callback = null;
function prepare_options_for_form(url, message_when_success) {
    if (_before_form_submit_callback != null)
        _before_form_submit_callback();
      
    details_form_options.url = url;
    details_form_options.success = function(response_json) {

        $(".input-validation-error").removeClass("input-validation-error");
        $("#error_messages").empty();
        // response_json = eval("(" + response_json + ")" );
        if (response_json.toString().substring(0, 30).toUpperCase().indexOf("<HTML") >= 0) {
            //the response is a html to display
            $("#error_messages").html(response_json);
        }
        else {
            if (response_json.type == "Error") {
                //Display the error message in each field
                violations = response_json.violations;
                err_html = "<p>The following errors ocurred:</p><ul>";
                for (var violation_idx = 0; violation_idx < violations.length;
                    violation_idx++) {
                    err_html += "<li>" +
                        violations[violation_idx].ErrorMessage + "</li>";
                    $("#" + violations[violation_idx].PropertyName
                        + "_field").addClass("input-validation-error");
                }
                $("#error_messages").html(err_html + "</ul>");
            }
            else {
                reset_grid_and_form(message_when_success);
            }
        }
    };
    return details_form_options;
}